package com.miracle.java2110.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.miracle.java2110.common.PageResult;
import com.miracle.java2110.common.R;
import com.miracle.java2110.listener.UploadOrderListener;
import com.miracle.java2110.service.OrderService;
import com.miracle.java2110.vo.OrderAddVo;
import com.miracle.java2110.vo.OrderTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 订单管理
 *
 * @Author: Wxl
 * @Date: 2021-11-11
 */
@CrossOrigin("http://127.0.0.1:5500") //允许此域发请求访问
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @RequestMapping("/table")
    public PageResult orderTable(@RequestParam Map<String, Object> params) {
        return orderService.findOrders(params);
    }

    @RequestMapping("/delete")
    public R deleteById(String id) {
        String[] ids;
        if (id.contains("[")) {
            ids = id.substring(1, id.lastIndexOf("]")).split(",");
        } else {
            ids = new String[]{id};
        }

        return orderService.deleteById(ids);
    }

    @RequestMapping("/getEdit")
    public OrderAddVo orderGetEdit(Integer id) {
        return orderService.getEdit(id);
    }

    @RequestMapping("/update")
    public R orderUpdate(OrderAddVo orderAddVo) {
        return orderService.orderUpdate(orderAddVo);
    }
    @RequestMapping("/detail")
    public List<OrderTreeVo> orderDetailById(Integer id) {
        return orderService.orderDeteilById(id);
    }

    @RequestMapping("/add")
    public R orderAdd(OrderAddVo orderAddVo) {
        return orderService.addOrder(orderAddVo);
    }

    @RequestMapping("/excelUpload")
    public R easyExcelUpload(MultipartFile file) {
        try {
            //获得一个工作簿对象    .xls
            //param1 文件流
            //param2 文件中每行数据要存储的实体类类型
            //param3 监听器   每读取一行数据 都会调用监听器的 invoke 方法 ，在invoke 方法中可以获取读取到的数据
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), OrderAddVo.class, new UploadOrderListener(orderService));

            //获得一个工作表对象    sheet
            ExcelReaderSheetBuilder sheet = read.sheet();

            // 读取工作表中的内容
            sheet.doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.ok(200, "导入成功");
    }
}
